<template>
  <div class="admin-management">
    <!-- 顶部导航 -->
    <header class="page-header">
      <p>管理员审核中心</p>
    </header>

    <!-- 选项卡导航 -->
    <div class="tabs-container">
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'review' }"
        @click="activeTab = 'review'"
      >
        待审核申请
      </button>
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'approved' }"
        @click="activeTab = 'approved'"
      >
        已审核列表
      </button>
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'merchants' }"
        @click="activeTab = 'merchants'"
      >
        商家管理
      </button>
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'businesses' }"
        @click="activeTab = 'businesses'"
      >
        店铺管理
      </button>
    </div>

    <!-- 待审核申请部分 -->
    <div v-if="activeTab === 'review'">
      <div class="review-container">
        <h3 class="section-title">待审核申请</h3>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <i class="fa fa-spinner fa-spin"></i> 加载中...
        </div>
        
        <!-- 错误提示 -->
        <div v-if="error" class="error-message">
          <i class="fa fa-exclamation-circle"></i> {{ error }}
          <button @click="loadApplications">重新加载</button>
        </div>
        
        <!-- 列表为空提示 -->
        <div class="empty-tip" v-if="!loading && pendingApplications.length === 0 && !error">
          <img src="https://img.icons8.com/fluency/96/000000/empty-box.png" alt="暂无申请" class="empty-icon">
          <p>暂无待审核的申请</p>
        </div>

        <!-- 申请列表 -->
        <ul class="application-list" v-if="!loading && pendingApplications.length > 0">
          <li class="app-item" v-for="(app, index) in pendingApplications" :key="index">
            <div class="app-header">
              <h4 class="app-title">{{ app.type === 'merchant' ? '商家注册申请' : '店铺创建申请' }}</h4>
              <span class="app-id">申请ID: {{ app.id }}</span>
            </div>
            
            <div class="app-content">
              <!-- 商家申请内容 -->
              <div v-if="app.type === 'merchant'" class="app-info">
                <div class="info-row">
                  <span class="info-label">申请类型:</span>
                  <span class="info-value">商家注册</span>
                </div>
                <div class="info-row">
                  <span class="info-label">用户名:</span>
                  <span class="info-value">{{ app.userData.username }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">负责人:</span>
                  <span class="info-value">{{ app.userData.lastName }}{{ app.userData.firstName }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">联系电话:</span>
                  <span class="info-value">{{ app.userData.phone }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">邮箱:</span>
                  <span class="info-value">{{ app.userData.email }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">申请时间:</span>
                  <span class="info-value">{{ formatDateTime(app.createdAt) }}</span>
                </div>
              </div>
              
              <!-- 店铺申请内容 -->
              <div v-if="app.type === 'business'" class="app-info">
                <div class="info-row">
                  <span class="info-label">申请类型:</span>
                  <span class="info-value">店铺创建</span>
                </div>
                <div class="info-row">
                  <span class="info-label">店铺名称:</span>
                  <span class="info-value">{{ app.businessData.businessName }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">店铺地址:</span>
                  <span class="info-value">{{ app.businessData.businessAddress }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">店铺简介:</span>
                  <span class="info-value">{{ app.businessData.businessExplain }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">起送价格:</span>
                  <span class="info-value">¥{{ app.businessData.startPrice }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">配送费用:</span>
                  <span class="info-value">¥{{ app.businessData.deliveryPrice }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">申请时间:</span>
                  <span class="info-value">{{ formatDateTime(app.createdAt) }}</span>
                </div>
              </div>
              
              <div class="app-actions" v-if="app.status === 'pending'">
                <button class="btn approve-btn" @click="approveApplication(app)">批准</button>
                <button class="btn reject-btn" @click="rejectApplication(app.id)">拒绝</button>
              </div>
              <div class="app-status" v-else>
                <span :class="['status-badge', `status-${app.status}`]">
                  {{ formatStatus(app.status) }}
                </span>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 已审核列表部分 -->
    <div v-if="activeTab === 'approved'">
      <div class="review-container">
        <h3 class="section-title">已审核申请</h3>
        
        <!-- 加载状态 -->
        <div v-if="loadingApproved" class="loading">
          <i class="fa fa-spinner fa-spin"></i> 加载中...
        </div>
        
        <!-- 列表为空提示 -->
        <div class="empty-tip" v-if="!loadingApproved && approvedApplications.length === 0">
          <img src="https://img.icons8.com/fluency/96/000000/empty-box.png" alt="暂无申请" class="empty-icon">
          <p>暂无已审核的申请</p>
        </div>

        <!-- 已审核申请列表 -->
        <ul class="application-list" v-if="!loadingApproved && approvedApplications.length > 0">
          <li class="app-item" v-for="(app, index) in approvedApplications" :key="index">
            <div class="app-header">
              <h4 class="app-title">{{ app.type === 'merchant' ? '商家注册申请' : '店铺创建申请' }}</h4>
              <span class="app-id">申请ID: {{ app.id }}</span>
            </div>
            
            <div class="app-content">
              <div class="app-info">
                <div class="info-row">
                  <span class="info-label">申请类型:</span>
                  <span class="info-value">{{ app.type === 'merchant' ? '商家注册' : '店铺创建' }}</span>
                </div>
                <div class="info-row" v-if="app.type === 'merchant'">
                  <span class="info-label">用户名:</span>
                  <span class="info-value">{{ app.userData.username }}</span>
                </div>
                <div class="info-row" v-if="app.type === 'business'">
                  <span class="info-label">店铺名称:</span>
                  <span class="info-value">{{ app.businessData.businessName }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">申请时间:</span>
                  <span class="info-value">{{ formatDateTime(app.createdAt) }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">审核时间:</span>
                  <span class="info-value">{{ formatDateTime(app.reviewedAt) }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">审核状态:</span>
                  <span class="info-value" :class="`status-${app.status}`">
                    {{ formatStatus(app.status) }}
                  </span>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 商家管理部分 -->
    <div v-if="activeTab === 'merchants'">
      <div class="management-container">
        <h3 class="section-title">商家管理</h3>
        
        <!-- 搜索与筛选区 -->
        <div class="search-filter-container">
          <div class="search-box">
            <i class="fa fa-search search-icon"></i>
            <input 
              type="text" 
              v-model="searchKey" 
              placeholder="搜索商家名称/手机号" 
              @input="handleSearch"
            >
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loadingMerchants" class="loading">
          <i class="fa fa-spinner fa-spin"></i> 加载中...
        </div>
        
        <!-- 错误提示 -->
        <div v-if="merchantsError" class="error-message">
          <i class="fa fa-exclamation-circle"></i> {{ merchantsError }}
          <button @click="loadMerchants">重新加载</button>
        </div>
        
        <!-- 列表为空提示 -->
        <div class="empty-tip" v-if="!loadingMerchants && merchants.length === 0 && !merchantsError">
          <img src="https://img.icons8.com/fluency/96/000000/empty-box.png" alt="暂无商家" class="empty-icon">
          <p>暂无商家数据</p>
        </div>

        <!-- 商家列表 -->
        <ul class="merchant-list" v-if="!loadingMerchants && merchants.length > 0">
          <li class="merchant-item" v-for="(merchant, index) in filteredMerchants" :key="index">
            <div class="merchant-info">
              <div class="merchant-avatar">
                <img :src="merchant.photo || 'https://placehold.co/60x60/EEE/666?text=商家'" alt="商家头像">
              </div>
              <div class="merchant-main">
                <div class="merchant-name-id">
                  <h3 class="merchant-name">{{ merchant.username || '未设置用户名' }}</h3>
                  <span class="merchant-id">ID: {{ merchant.id }}</span>
                </div>
                <p class="merchant-realname">负责人：{{ formatUserName(merchant) }}</p>
                <div class="merchant-contact">
                  <p class="merchant-email" v-if="merchant.email">
                    <i class="fa fa-envelope"></i> {{ merchant.email }}
                  </p>
                  <p class="merchant-phone" v-if="merchant.phone">
                    <i class="fa fa-phone"></i> {{ merchant.phone }}
                  </p>
                </div>
                <p class="merchant-time">创建时间：{{ formatDateTime(merchant.createTime) }}</p>
              </div>
            </div>

            <div class="merchant-actions">
              <button class="btn view-btn" @click="handleViewMerchantDetail(merchant)">查看详情</button>
              <button class="btn delete-btn" @click="handleDeleteMerchant(merchant)">删除</button>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 店铺管理部分 -->
    <div v-if="activeTab === 'businesses'">
      <div class="management-container">
        <h3 class="section-title">店铺管理</h3>
        
        <!-- 搜索与筛选区 -->
        <div class="search-filter-container">
          <div class="search-box">
            <i class="fa fa-search search-icon"></i>
            <input 
              type="text" 
              v-model="searchBusinessKey" 
              placeholder="搜索店铺名称/地址" 
              @input="handleBusinessSearch"
            >
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loadingBusinesses" class="loading">
          <i class="fa fa-spinner fa-spin"></i> 加载中...
        </div>
        
        <!-- 错误提示 -->
        <div v-if="businessesError" class="error-message">
          <i class="fa fa-exclamation-circle"></i> {{ businessesError }}
          <button @click="loadBusinesses">重新加载</button>
        </div>
        
        <!-- 列表为空提示 -->
        <div class="empty-tip" v-if="!loadingBusinesses && businesses.length === 0 && !businessesError">
          <img src="https://img.icons8.com/fluency/96/000000/empty-box.png" alt="暂无店铺" class="empty-icon">
          <p>暂无店铺数据</p>
        </div>

        <!-- 店铺列表 -->
        <ul class="business-list" v-if="!loadingBusinesses && businesses.length > 0">
          <li class="business-item" v-for="(business, index) in filteredBusinesses" :key="index">
            <div class="business-info">
              <div class="business-cover">
                <img :src="business.businessImg || 'https://via.placehold.co/150?text=店铺图片'" alt="店铺封面">
              </div>
              <div class="business-main">
                <h3 class="business-name">{{ business.businessName }}</h3>
                <p class="business-address"><i class="fa fa-map-marker"></i> {{ business.businessAddress }}</p>
                <p class="business-explain">{{ business.businessExplain }}</p>
                <p class="business-price">
                  <i class="fa fa-tag"></i> 起送: ¥{{ business.startPrice }} | 配送: ¥{{ business.deliveryPrice }}
                </p>
                <p class="business-time">创建时间：{{ formatDateTime(business.createTime) }}</p>
              </div>
            </div>

            <div class="business-actions">
              <button class="btn view-btn" @click="handleViewBusinessDetail(business)">查看详情</button>
              <button class="btn delete-btn" @click="handleDeleteBusiness(business)">删除</button>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 查看详情弹窗 -->
    <div class="modal-mask" v-if="showDetailModal">
      <div class="modal-content">
        <div class="modal-header">
          <h4>{{ detailType === 'merchant' ? '商家详情' : '店铺详情' }}</h4>
          <i class="fa fa-times close-icon" @click="showDetailModal = false"></i>
        </div>
        <div class="modal-body">
          <!-- 商家详情 -->
          <div v-if="detailType === 'merchant'">
            <div class="detail-avatar">
              <img :src="currentMerchant.photo || 'https://via.placehold.co/100?text=商家'" alt="商家头像">
            </div>
            <div class="detail-info">
              <div class="detail-item">
                <span class="detail-label">商家ID：</span>
                <span class="detail-value">{{ currentMerchant.id }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">用户名：</span>
                <span class="detail-value">{{ currentMerchant.username || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">负责人：</span>
                <span class="detail-value">{{ formatUserName(currentMerchant) }}</span>
              </div>
              <div class="detail-item" v-if="currentMerchant.email">
                <span class="detail-label">邮箱：</span>
                <span class="detail-value">{{ currentMerchant.email }}</span>
              </div>
              <div class="detail-item" v-if="currentMerchant.phone">
                <span class="detail-label">手机号：</span>
                <span class="detail-value">{{ currentMerchant.phone }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">性别：</span>
                <span class="detail-value">{{ formatGender(currentMerchant.gender) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">创建时间：</span>
                <span class="detail-value">{{ formatDateTime(currentMerchant.createTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">更新时间：</span>
                <span class="detail-value">{{ formatDateTime(currentMerchant.updateTime) }}</span>
              </div>
            </div>
          </div>
          
          <!-- 店铺详情 -->
          <div v-if="detailType === 'business'">
            <div class="detail-avatar">
              <img :src="currentBusiness.businessImg || 'https://via.placehold.co/100?text=店铺'" alt="店铺图片">
            </div>
            <div class="detail-info">
              <div class="detail-item">
                <span class="detail-label">店铺ID：</span>
                <span class="detail-value">{{ currentBusiness.id }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">店铺名称：</span>
                <span class="detail-value">{{ currentBusiness.businessName }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">店铺地址：</span>
                <span class="detail-value">{{ currentBusiness.businessAddress }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">店铺简介：</span>
                <span class="detail-value">{{ currentBusiness.businessExplain }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">起送价格：</span>
                <span class="detail-value">¥{{ currentBusiness.startPrice }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">配送费用：</span>
                <span class="detail-value">¥{{ currentBusiness.deliveryPrice }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">创建时间：</span>
                <span class="detail-value">{{ formatDateTime(currentBusiness.createTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">更新时间：</span>
                <span class="detail-value">{{ formatDateTime(currentBusiness.updateTime) }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="showDetailModal = false">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AdminManagement',
  data() {
    return {
      // 选项卡状态
      activeTab: 'review',
      
      // 申请管理相关
      pendingApplications: [],
      approvedApplications: [],
      loading: false,
      loadingApproved: false,
      error: null,
      
      // 商家管理相关
      searchKey: '',
      merchants: [],
      loadingMerchants: false,
      merchantsError: null,
      
      // 店铺管理相关
      searchBusinessKey: '',
      businesses: [],
      loadingBusinesses: false,
      businessesError: null,
      
      // 弹窗相关
      showDetailModal: false,
      detailType: 'merchant', // 'merchant' or 'business'
      currentMerchant: {},
      currentBusiness: {}
    }
  },
  created() {
    // 先验证权限，通过后再加载数据
    if (this.checkAdminPermission()) {
      this.loadApplications();
      this.loadApprovedApplications();
      this.loadMerchants();
      this.loadBusinesses();
    }
  },
  computed: {
    // 筛选后的商家列表
    filteredMerchants() {
      return this.merchants.filter(merchant => {
        const searchMatch = this.searchKey === ''
          ? true
          : (merchant.username || '').includes(this.searchKey) || 
            (merchant.email || '').includes(this.searchKey) || 
            (merchant.phone || '').includes(this.searchKey);
        
        return searchMatch;
      });
    },
    
    // 筛选后的店铺列表
    filteredBusinesses() {
      return this.businesses.filter(business => {
        const searchMatch = this.searchBusinessKey === ''
          ? true
          : (business.businessName || '').includes(this.searchBusinessKey) || 
            (business.businessAddress || '').includes(this.searchBusinessKey);
        
        return searchMatch;
      });
    },
    
    // 统一判断登录状态
    isLoggedIn() {
      const storedUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      return !!storedUser;
    },
    
    // 统一获取token
    authToken() {
       return localStorage.getItem('jwt_token'); 
    }
  },
  methods: {
    // 检查管理员权限
    checkAdminPermission() {
      // 检查是否登录
      if (!this.isLoggedIn) {
        alert('请先登录');
        this.$router.push('/login');
        return false;
      }
      
      // 获取当前用户信息（使用localStorage统一存储）
      const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      
      // 检查是否有管理员权限
      if (!currentUser || !currentUser.authorities || 
          !currentUser.authorities.some(auth => auth.name === 'ADMIN')) {
        alert('您没有管理员权限，无法访问此页面');
        this.$router.push('/userCenter');
        return false;
      }
      
      return true;
    },
    
    // 加载待审核申请
    async loadApplications() {
      this.loading = true;
      this.error = null;
      
      try {
        // 从localStorage获取所有申请
        const allApplications = JSON.parse(
          localStorage.getItem('allApplications') || '[]'
        );
        
        // 筛选出待审核的申请
        this.pendingApplications = allApplications.filter(app => app.status === 'pending');
      } catch (error) {
        console.error('加载申请失败:', error);
        this.error = '加载申请失败';
      } finally {
        this.loading = false;
      }
    },
    
    // 加载已审核申请
    async loadApprovedApplications() {
      this.loadingApproved = true;
      
      try {
        // 从localStorage获取所有申请
        const allApplications = JSON.parse(
          localStorage.getItem('allApplications') || '[]'
        );
        
        // 筛选出已审核的申请
        this.approvedApplications = allApplications.filter(app => app.status !== 'pending');
      } catch (error) {
        console.error('加载已审核申请失败:', error);
      } finally {
        this.loadingApproved = false;
      }
    },
    
    // 加载商家数据
    async loadMerchants() {
      this.loadingMerchants = true;
      this.merchantsError = null;
      
      try {
        // 使用统一的token获取方式
        const token = this.authToken;
        if (!token) {
          throw new Error('未找到认证信息，请重新登录');
        }
        
        const headers = {
          'Authorization': `Bearer ${token}`
        };
        
        // 获取所有用户，然后筛选出商家
        const response = await this.$axios.get('/api/persons', { headers });
        
        // 筛选出商家用户（拥有BUSINESS权限的用户）
        this.merchants = response.data.filter(person => 
          person.authorities && person.authorities.some(auth => auth.name === 'BUSINESS')
        );
      } catch (error) {
        console.error('加载商家数据失败:', error);
        this.merchantsError = error.response?.data?.message || error.message || '加载商家数据失败';
        
        // 处理403权限错误
        if (error.response && error.response.status === 403) {
          alert('权限不足，请使用管理员账号登录');
          this.$router.push('/login');
        }
      } finally {
        this.loadingMerchants = false;
      }
    },
    
    // 加载店铺数据
    async loadBusinesses() {
      this.loadingBusinesses = true;
      this.businessesError = null;
      
      try {
        // 使用统一的token获取方式
        const token = this.authToken;
        if (!token) {
          throw new Error('未找到认证信息，请重新登录');
        }
        
        const headers = {
          'Authorization': `Bearer ${token}`
        };
        
        // 获取店铺列表
        const response = await this.$axios.get('/api/businesses', { headers });
        
        // 根据API响应格式，数据在data字段中
        this.businesses = response.data.data || [];
        
      } catch (error) {
        console.error('加载店铺数据失败:', error);
        this.businessesError = error.response?.data?.message || error.message || '加载店铺数据失败';
        
        // 处理403权限错误
        if (error.response && error.response.status === 403) {
          alert('权限不足，请使用管理员账号登录');
          this.$router.push('/login');
        }
      } finally {
        this.loadingBusinesses = false;
      }
    },
    
    // 格式化用户姓名
    formatUserName(user) {
      if (user.firstName && user.lastName) {
        return `${user.lastName}${user.firstName}`;
      }
      return user.firstName || user.lastName || '未设置';
    },
    
    // 格式化性别
    formatGender(gender) {
      if (!gender) return '未设置';
      return gender === 'MALE' ? '男' : gender === 'FEMALE' ? '女' : gender;
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    },
    
    // 格式化状态
    formatStatus(status) {
      switch (status) {
        case 'pending': return '待审核';
        case 'approved': return '已批准';
        case 'rejected': return '已拒绝';
        default: return status;
      }
    },
    
    // 搜索商家
    handleSearch() {
      // 依赖computed自动筛选，无需额外逻辑
    },
    
    // 搜索店铺
    handleBusinessSearch() {
      // 依赖computed自动筛选，无需额外逻辑
    },
    
    // 查看商家详情
    handleViewMerchantDetail(merchant) {
      this.detailType = 'merchant';
      this.currentMerchant = merchant;
      this.showDetailModal = true;
    },
    
    // 查看店铺详情
    handleViewBusinessDetail(business) {
      this.detailType = 'business';
      this.currentBusiness = business;
      this.showDetailModal = true;
    },
    
    // 删除商家
    async handleDeleteMerchant(merchant) {
      if (!confirm(`确定要删除商家 "${merchant.username}" 吗？此操作不可撤销。`)) {
        return;
      }
      
      try {
        // 使用统一的token获取方式
        const token = this.authToken;
        const headers = {
          'Authorization': `Bearer ${token}`
        };
        
        await this.$axios.delete(`/api/persons/${merchant.id}`, { headers });
        alert('商家删除成功');
        this.loadMerchants();
      } catch (error) {
        console.error('删除商家失败:', error);
        alert('删除商家失败: ' + (error.response?.data?.message || error.message));
        
        // 处理403权限错误
        if (error.response && error.response.status === 403) {
          alert('权限不足，请使用管理员账号登录');
          this.$router.push('/login');
        }
      }
    },
    
    // 删除店铺
    async handleDeleteBusiness(business) {
      if (!confirm(`确定要删除店铺 "${business.businessName}" 吗？此操作不可撤销。`)) {
        return;
      }
      
      try {
        // 使用统一的token获取方式
        const token = this.authToken;
        const headers = {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        };
        
        // 调用DELETE /api/businesses/{id}接口
        const response = await this.$axios.delete(`/api/businesses/${business.id}`, { headers });
        
        // 处理API响应
        if (response.data && response.data.success) {
          alert('店铺删除成功');
          this.loadBusinesses(); // 重新加载店铺列表
        } else {
          alert('删除失败: ' + (response.data?.message || '未知错误'));
        }
      } catch (error) {
        console.error('删除店铺失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '删除店铺失败';
        alert(`删除店铺失败: ${errorMsg}`);
        
        // 处理403权限错误
        if (error.response && error.response.status === 403) {
          alert('权限不足，只有管理员可以删除店铺');
          this.$router.push('/login');
        }
      }
    },
    
    // 批准申请
    async approveApplication(application) {
      try {
        const token = this.authToken;
        if (!token) {
          alert('请先以管理员身份登录');
          return;
        }
        
        const headers = {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        };
        
        if (application.type === 'merchant') {
          // 商家注册批准
          await this.approveMerchantApplication(application, headers);
        } else if (application.type === 'business') {
          // 店铺创建批准
          await this.approveBusinessApplication(application, headers);
        }
      } catch (error) {
        console.error('批准申请失败:', error);
        this.handleApproveError(error);
      }
    },
    
    // 处理商家申请批准
    async approveMerchantApplication(application, headers) {
      // 构建完整的商家数据，符合API要求
      const merchantData = {
        username: application.userData.username,
        firstName: application.userData.firstName || '',
        lastName: application.userData.lastName || '',
        email: application.userData.email || '',
        phone: application.userData.phone || '',
        gender: application.userData.gender || 'MALE', // 必需字段
        photo: application.userData.photo || '', // 必需字段，可以为空
        authorities: [
          { 
            name: 'BUSINESS' // 商家权限
          }
        ]
      };
      
      console.log('创建商家用户请求数据:', JSON.stringify(merchantData, null, 2));
      
      const response = await this.$axios.post('/api/persons', merchantData, { 
        headers,
        timeout: 10000
      });
      
      console.log('创建商家用户响应:', response);
      
      if (response.status >= 200 && response.status < 300) {
        this.updateApplicationStatus(application.id, 'approved');
        alert('商家账户创建成功！');
        
        setTimeout(() => {
          this.loadMerchants();
        }, 500);
      } else {
        throw new Error(`创建商家失败，状态码: ${response.status}`);
      }
    },
    
    // 处理店铺申请批准
    async approveBusinessApplication(application, headers) {
      const businessOwnerId = application.userId || 
                             (application.userData && application.userData.id);
      
      if (!businessOwnerId) {
        alert('错误：无法找到商家信息，申请数据不完整');
        return;
      }
      
      const businessData = {
        businessName: application.businessData.businessName || '未命名店铺',
        businessAddress: application.businessData.businessAddress || '未设置地址',
        businessExplain: application.businessData.businessExplain || '',
        businessImg: application.businessData.businessImg || '',
        startPrice: parseFloat(application.businessData.startPrice) || 0,
        deliveryPrice: parseFloat(application.businessData.deliveryPrice) || 0,
        remarks: application.businessData.remarks || '管理员审核通过',
        orderTypeId: parseInt(application.businessData.orderTypeId) || 0,
        businessOwner: {
          id: businessOwnerId
        }
      };
      
      console.log('创建店铺请求数据:', businessData);
      
      const response = await this.$axios.post('/api/businesses', businessData, { 
        headers,
        timeout: 10000
      });
      
      console.log('完整的API响应:', response);
      
      if (response.status >= 200 && response.status < 300) {
        if (response.data && response.data.businessName) {
          this.updateApplicationStatus(application.id, 'approved');
          alert(`店铺 "${response.data.businessName}" 创建成功！`);
        } else {
          this.updateApplicationStatus(application.id, 'approved');
          alert('店铺申请已批准！');
        }
        
        setTimeout(() => {
          this.loadBusinesses();
        }, 500);
      } else {
        throw new Error(`创建店铺失败，状态码: ${response.status}`);
      }
    },
    
    // 处理批准申请错误
    handleApproveError(error) {
      if (error.response) {
        const status = error.response.status;
        const data = error.response.data;
        
        console.error('错误响应详情:', status, data);
        
        switch (status) {
          case 400:
            alert(`请求数据错误: ${data?.message || '请检查字段格式和必填项'}`);
            break;
          case 401:
            alert('登录已过期，请重新登录');
            this.$router.push('/login');
            break;
          case 403:
            alert('权限不足，请使用管理员账号');
            this.$router.push('/login');
            break;
          case 409:
            alert('店铺名称已存在，请使用其他名称');
            break;
          case 500:
            alert('服务器内部错误，请稍后重试');
            break;
          default:
            alert(`操作失败: ${data?.message || `状态码: ${status}`}`);
        }
      } else if (error.request) {
        alert('网络连接失败，请检查网络设置');
      } else {
        alert(`操作失败: ${error.message}`);
      }
    },
    
    // 通知商家（可选）
    notifyMerchant(application, status) {
      console.log(`通知商家 ${application.applicant}: 申请${status === 'approved' ? '通过' : '拒绝'}`);
    },
    
    // 拒绝申请
    rejectApplication(id) {
      this.updateApplicationStatus(id, 'rejected');
      alert('已拒绝该申请');
    },
    
    // 更新申请状态
    updateApplicationStatus(applicationId, newStatus) {
      // 从localStorage获取所有申请
      const allApplications = JSON.parse(
        localStorage.getItem('allApplications') || '[]'
      );
      
      // 更新状态并添加审核时间
      const updatedApplications = allApplications.map(app => {
        if (app.id === applicationId) {
          return { 
            ...app, 
            status: newStatus,
            reviewedAt: new Date().toISOString()
          };
        }
        return app;
      });
      
      // 保存回localStorage
      localStorage.setItem('allApplications', JSON.stringify(updatedApplications));
      
      // 重新加载申请列表
      this.loadApplications();
      this.loadApprovedApplications();
    }
  }
}
</script>


<style scoped>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 页面容器 */
.admin-management {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 12vw;
  padding-bottom: 15vw;
}

/* 顶部导航 */
.page-header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 选项卡容器 */
.tabs-container {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 3vw;
}

.tab-button {
  flex: 1;
  padding: 4vw 0;
  font-size: 3.5vw;
  background: none;
  border: none;
  border-bottom: 3px solid transparent;
  cursor: pointer;
  color: #666;
}

.tab-button.active {
  color: #0097FF;
  border-bottom: 3px solid #0097FF;
  font-weight: bold;
}

/* 审核容器 */
.review-container {
  width: 100%;
  padding: 3vw;
}

.management-container {
  width: 100%;
  padding: 3vw;
}

.section-title {
  font-size: 4vw;
  color: #333;
  margin-bottom: 3vw;
  padding-bottom: 2vw;
  border-bottom: 1px solid #eee;
}

/* 搜索与筛选容器 */
.search-filter-container {
  width: 100%;
  padding: 3vw;
  display: flex;
  gap: 2vw;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 3vw;
}

/* 搜索框 */
.search-box {
  flex: 1;
  height: 10vw;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 0 3vw;
}

.search-icon {
  font-size: 3.5vw;
  color: #999;
  margin-right: 2vw;
}

.search-box input {
  flex: 1;
  height: 100%;
  background: transparent;
  border: none;
  outline: none;
  font-size: 3.2vw;
  color: #333;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 10vw;
  font-size: 4vw;
  color: #0097FF;
}

/* 错误提示 */
.error-message {
  background-color: #fff2f0;
  border: 1px solid #ccc7;
  border-radius: 6px;
  padding: 4vw;
  margin: 4vw 3vw;
  color: #f5222d;
  text-align: center;
  font-size: 3.5vw;
}

.error-message button {
  margin-top: 3vw;
  padding: 2vw 4vw;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 空列表提示 */
.empty-tip {
  width: 100%;
  padding: 15vw 0;
  text-align: center;
  color: #999;
}

.empty-icon {
  width: 20vw;
  height: 20vw;
  margin-bottom: 3vw;
  opacity: 0.6;
}

.empty-tip p {
  font-size: 3.2vw;
}

/* 申请列表 */
.application-list {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

/* 商家列表 */
.merchant-list {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

/* 店铺列表 */
.business-list {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

/* 申请项 */
.app-item {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  padding: 3vw;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
  padding-bottom: 2vw;
  border-bottom: 1px solid #f0f0f0;
}

.app-title {
  font-size: 3.5vw;
  color: #333;
  font-weight: 600;
}

.app-id {
  font-size: 2.8vw;
  color: #999;
}

.app-content {
  display: flex;
  flex-direction: column;
  gap: 2vw;
}

.app-info {
  display: flex;
  flex-direction: column;
  gap: 1.5vw;
}

.info-row {
  display: flex;
}

.info-label {
  width: 25%;
  font-size: 3vw;
  color: #666;
  font-weight: 500;
}

.info-value {
  width: 75%;
  font-size: 3vw;
  color: #333;
}

.app-actions {
  display: flex;
  gap: 2vw;
  margin-top: 2vw;
}

.app-status {
  display: flex;
  justify-content: flex-end;
  margin-top: 2vw;
}

.status-badge {
  padding: 1vw 2vw;
  border-radius: 2vw;
  font-size: 2.8vw;
  font-weight: 500;
}

.status-pending {
  background-color: #fffbe6;
  color: #faad14;
}

.status-approved {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-rejected {
  background-color: #fff2f0;
  color: #ff4d4f;
}

/* 商家列表项 */
.merchant-item {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  padding: 3vw;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 店铺列表项 */
.business-item {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  padding: 3vw;
  display: flex;
  flex-direction: column;
  gap: 2vw;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 商家基础信息 */
.merchant-info {
  display: flex;
  align-items: center;
  gap: 3vw;
  flex: 1;
}

/* 店铺基础信息 */
.business-info {
  display: flex;
  align-items: center;
  gap: 3vw;
}

/* 商家头像 */
.merchant-avatar {
  width: 15vw;
  height: 15vw;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #f0f0f0;
}

.merchant-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 店铺封面 */
.business-cover {
  width: 25vw;
  height: 15vw;
  border-radius: 4px;
  overflow: hidden;
}

.business-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商家核心信息 */
.merchant-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1.5vw;
}

/* 店铺核心信息 */
.business-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1.5vw;
}

/* 商家名+ID */
.merchant-name-id {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.merchant-name {
  font-size: 3.5vw;
  color: #333;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.merchant-id {
  font-size: 2.8vw;
  color: #999;
}

/* 店铺名称 */
.business-name {
  font-size: 3.5vw;
  color: #333;
  font-weight: 600;
}

/* 负责人姓名 */
.merchant-realname {
  font-size: 3vw;
  color: #666;
}

/* 店铺地址 */
.business-address {
  font-size: 3vw;
  color: #666;
}

/* 店铺简介 */
.business-explain {
  font-size: 3vw;
  color: #666;
}

/* 店铺价格 */
.business-price {
  font-size: 3vw;
  color: #666;
}

/* 联系方式 */
.merchant-contact {
  display: flex;
  flex-direction: column;
  gap: 1vw;
  font-size: 2.8vw;
  color: #666;
}

.merchant-contact i {
  margin-right: 1vw;
}

.merchant-time {
  font-size: 2.8vw;
  color: #999;
}

.business-time {
  font-size: 2.8vw;
  color: #999;
}

/* 操作按钮 */
.merchant-actions {
  display: flex;
  gap: 2vw;
}

.business-actions {
  display: flex;
  gap: 2vw;
  justify-content: flex-end;
}

/* 按钮样式 */
.btn {
  padding: 1.5vw 3vw;
  border-radius: 4px;
  font-size: 3vw;
  font-weight: 500;
  border: none;
  cursor: pointer;
}

.view-btn {
  background-color: #e6f4ff;
  color: #0097FF;
}

.delete-btn {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.approve-btn {
  background-color: #e6f7ef;
  color: #38CA73;
}

.reject-btn {
  background-color: #fff2f0;
  color: #ff4d4f;
}

/* 弹窗遮罩 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

/* 弹窗内容 */
.modal-content {
  width: 85%;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

/* 弹窗头部 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3vw 3vw;
  border-bottom: 1px solid #f5f5f5;
}

.modal-header h4 {
  font-size: 3.5vw;
  color: #333;
  font-weight: 600;
}

.close-icon {
  font-size: 4vw;
  color: #999;
  cursor: pointer;
}

/* 弹窗主体 */
.modal-body {
  padding: 3vw;
}

/* 详情页头像 */
.detail-avatar {
  width: 25vw;
  height: 25vw;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #f0f0f0;
  margin: 0 auto 3vw;
}

.detail-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 详情信息列表 */
.detail-info {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 2.5vw;
}

/* 详情项 */
.detail-item {
  display: flex;
  font-size: 3.2vw;
}

.detail-label {
  width: 28%;
  color: #666;
  font-weight: 500;
}

.detail-value {
  width: 72%;
  color: #333;
}

/* 弹窗底部 */
.modal-footer {
  padding: 3vw;
  border-top: 1px solid #f5f5f5;
}

.confirm-btn {
  width: 100%;
  height: 11vw;
  background-color: #0097FF;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 3.2vw;
  font-weight: 500;
  cursor: pointer;
}
</style>
